package com.linchong.concurrency.chapter9;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author:linchong
 * @CreateTime:2020-01-09 11:10
 * @Description:多线程下的生产者-消费者
 */
@Slf4j
public class ProduceConsumerVersion1 {
	private int i = 1;
	final private Object LOCK = new Object();

	private void produce() {
		synchronized (LOCK) {
			try {
				Thread.sleep(1_000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			log.info("produce:{}", (i++));
		}
	}

	private void consume() {
		synchronized (LOCK) {
			try {
				Thread.sleep(1_000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			log.info("Consumer:{}", (i--));
		}
	}

	public static void main(String[] args) {
		ProduceConsumerVersion1 pc = new ProduceConsumerVersion1();
		new Thread("Produce") {
			@Override
			public void run() {
				while (true) {
					pc.produce();
				}
			}
		}.start();

		new Thread("Consumer") {
			@Override
			public void run() {
				while (true) {
					pc.consume();
				}
			}
		}.start();

	}
}
